package com.panshi.repast.Util;

import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.RandomAccessFile;

import android.graphics.Bitmap;

public class SaveBitmapToSD {
	/**
	 * Store image to SD card.
	 */
	public static String storeImageToFile(Bitmap bitmap, String str) {
		if (bitmap == null) {
			return "no bitmap";
		}

		File file = null;
		RandomAccessFile accessFile = null;
		String path = "/mnt/sdcard";
		path = path + "/" + str + ".png";
		file = new File(path);
		if (!file.exists()) {
			file.mkdir();
		}
		ByteArrayOutputStream steam = new ByteArrayOutputStream();
		bitmap.compress(Bitmap.CompressFormat.PNG, 100, steam);
		byte[] buffer = steam.toByteArray();

		try {
			accessFile = new RandomAccessFile(file, "rw");
			accessFile.write(buffer);
		} catch (Exception e) {
			return e.toString();
		}

		try {
			steam.close();
			accessFile.close();
		} catch (IOException e) {
			// Note: do nothing.
			path = "save fail";
		}

		return path;
	}

	/**
	 * 保存图片
	 * 
	 * @param bm
	 *            bitmap
	 * @param fileName
	 *            文件名字
	 * @throws IOException
	 */
	public static String saveFile(Bitmap bm, String fileName)
			throws IOException {
		String str = "/mnt/sdcard/";
		File dirFile = new File(str);
		if (!dirFile.exists()) {
			dirFile.mkdir();
		}
		File myCaptureFile = new File(str + fileName + ".jpg");
		BufferedOutputStream bos = new BufferedOutputStream(
				new FileOutputStream(myCaptureFile));
		bm.compress(Bitmap.CompressFormat.JPEG, 80, bos);
		bos.flush();
		bos.close();
		return dirFile.toString();
	}
}
